package com.mzj.saas.jobs.commons;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * @Author: wangrl
 * @Description: HttpRequest 请求工具类
 * @Date: 11:29 2018/5/3
 * @Version: 1.0
 */
public class HttpClientUtil {
	//连接超时时间，默认10秒
    private static final int socketTimeout = 10000;

    //传输超时时间，默认30秒
    private static final int connectTimeout = 30000;

    public static String ContentTypeXML = "text/xml"; //xml请求格式

	public static String ContentTypeJSON = "application/json; charset=utf-8"; //JSON请求格式

	/**
	 * url 请求路径
	 * params 参数
	 * contentType 请求头类型
	 * @throws IOException
	 * @throws ClientProtocolException
	 * @throws NoSuchAlgorithmException
	 * @throws KeyStoreException
	 * @throws KeyManagementException
	 * @throws UnrecoverableKeyException
	 */
	@SuppressWarnings("deprecation")
    public static String httpPost(String url, String postData,String contentType) throws IOException, UnrecoverableKeyException, KeyManagementException, KeyStoreException, NoSuchAlgorithmException {

		HttpPost httpPost = new HttpPost(url);
		//得指明使用UTF-8编码，否则到API服务器XML的中文不能被成功识别
		StringEntity postEntity = new StringEntity(postData, "UTF-8");
        httpPost.addHeader("Content-Type", contentType);
        httpPost.setEntity(postEntity);

        //设置请求器的配置
		// 构建请求配置信息
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout) // 创建连接的最长时间
				.setConnectionRequestTimeout(500) // 从连接池中获取到连接的最长时间
				.setSocketTimeout(socketTimeout) // 数据传输的最长时间
				.setStaleConnectionCheckEnabled(true) // 提交请求前测试连接是否可用
				.build();
        httpPost.setConfig(requestConfig);

        HttpClient httpClient = HttpClients.createDefault();
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        return EntityUtils.toString(entity, "UTF-8");
	}

	/**
	 * @param url 请求路径
	 * @param params 参数
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("deprecation")
    public static String httpGet(String url, Map<String,Object> params) throws Exception {
		int i = 0;
		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append(url);
		for(Map.Entry<String,Object> entry : params.entrySet()){
			stringBuffer.append(i == 0 ? "?" : "&").append(entry.getKey()).append("="+entry.getValue());
			i++;
		}
		// 创建Httpclient对象
		CloseableHttpClient httpclient = HttpClients.createDefault();
		// 创建http GET请求
		HttpGet httpGet = new HttpGet(stringBuffer.toString());
		// 构建请求配置信息
		RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTimeout) // 创建连接的最长时间
				.setConnectionRequestTimeout(500) // 从连接池中获取到连接的最长时间
				.setSocketTimeout(socketTimeout) // 数据传输的最长时间
				.setStaleConnectionCheckEnabled(true) // 提交请求前测试连接是否可用
				.build();
		// 设置请求配置信息
		httpGet.setConfig(config);
		CloseableHttpResponse response = null;
		try {
			// 执行请求
			response = httpclient.execute(httpGet);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				 return EntityUtils.toString(response.getEntity(), "UTF-8");
			}
		} finally {
			if (response != null) {
				response.close();
			}
			httpclient.close();
		}
		return null;
	}

	@SuppressWarnings("deprecation")
    public static byte[] httpGetForByte(String url,Map<String,Object> params) throws Exception {
		int i = 0;
		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append(url);
		for(Map.Entry<String,Object> entry : params.entrySet()){
			stringBuffer.append(i == 0 ? "?" : "&").append(entry.getKey()).append("="+entry.getValue());
			i++;
		}
		// 创建Httpclient对象
		CloseableHttpClient httpclient = HttpClients.createDefault();
		// 创建http GET请求
		HttpGet httpGet = new HttpGet(stringBuffer.toString());
		// 构建请求配置信息
		RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTimeout) // 创建连接的最长时间
				.setConnectionRequestTimeout(500) // 从连接池中获取到连接的最长时间
				.setSocketTimeout(socketTimeout) // 数据传输的最长时间
				.setStaleConnectionCheckEnabled(true) // 提交请求前测试连接是否可用
				.build();
		// 设置请求配置信息
		httpGet.setConfig(config);
		CloseableHttpResponse response = null;
		try {
			// 执行请求
			response = httpclient.execute(httpGet);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				return EntityUtils.toByteArray(response.getEntity());
			}
		} finally {
			if (response != null) {
				response.close();
			}
			httpclient.close();
		}
		return null;
	}


}
